package org.kjtc.balanceService;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.kjtc.balanceEntity.MeterRecord;
import org.kjtc.service.BaseService;
import org.kjtc.util.Const;
import org.kjtc.util.FileDownload;
import org.kjtc.util.ImageCut;
import org.kjtc.util.Tools;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service("meterRecordService")
public class MeterRecordService extends BaseService {

	@SuppressWarnings("unchecked")
	public List<MeterRecord> getMeterRecordCount(MeterRecord meterRecord) throws Exception {
		return (List<MeterRecord>)this.getDaoSupport().findForList("T_MeterRecord.getMeterRecordCount", meterRecord);
	}

	@SuppressWarnings("unchecked")
	public List<MeterRecord> getMeterRecord(MeterRecord meterRecord) throws Exception {
		return (List<MeterRecord>) this.getDaoSupport().findForList("T_MeterRecord.getMeterRecord", meterRecord);
	}

	@SuppressWarnings("unchecked")
	public List<MeterRecord> getMeter(MeterRecord meterRecord) throws Exception {
		return (List<MeterRecord>) this.getDaoSupport().findForList("T_MeterRecord.getMeter", meterRecord);
	}

	@SuppressWarnings("unchecked")
	public List<MeterRecord> getMeterMsg(MeterRecord meterRecord) throws Exception {
		return (List<MeterRecord>) this.getDaoSupport().findForList("T_MeterRecord.getMeterMsg", meterRecord);
	}

	public int saveMeterRecord(JSONArray meterRecordArray, String userID) throws Exception {
		List<MeterRecord> meterRecords = jsonArray2List(meterRecordArray, userID);
		return (int) this.getDaoSupport().save("T_MeterRecord.insert", meterRecords);
	}
	
	public int importMeterRecord(List<MeterRecord> meterRecords) throws Exception {
		return (int) this.getDaoSupport().save("T_MeterRecord.importMeterRecord", meterRecords);
	}

	public int updateMeterRecord(JSONArray meterRecordArray, String userID) throws Exception {
		List<MeterRecord> meterRecords = jsonArray2List(meterRecordArray, userID);
		return (int) this.getDaoSupport().save("T_MeterRecord.update", meterRecords);
	}

	public int deleteMeterRecord(MeterRecord meterRecord) throws Exception {
		return (int) this.getDaoSupport().save("T_MeterRecord.delete", meterRecord);
	}

	private List<MeterRecord> jsonArray2List(JSONArray meterRecordArray, String userID) {
		List<MeterRecord> meterRecords = new ArrayList<MeterRecord>();
		Date date = new Date();
		for (int i = 0; i < meterRecordArray.size(); i++) {
			JSONObject meterRecordJson = meterRecordArray.getJSONObject(i);
			MeterRecord meterRecord = new MeterRecord();
			if (meterRecordJson.has("ID") && meterRecordJson.getString("ID") != null && !meterRecordJson.getString("ID").isEmpty()) {
				meterRecord.setID(Integer.parseInt(meterRecordJson.getString("ID")));
			}
			if (meterRecordJson.has("chargingStationID")) {
				meterRecord.setChargingStationID(meterRecordJson.getString("chargingStationID"));
			}
			if (meterRecordJson.has("meterCode")) {
				meterRecord.setMeterCode(meterRecordJson.getString("meterCode"));
			}
			if (meterRecordJson.has("meterDate")) {
				meterRecord.setMeterDate(meterRecordJson.getString("meterDate"));
			}
			if (meterRecordJson.has("meterTime")) {
				meterRecord.setMeterTime(meterRecordJson.getString("meterTime"));
			}
			if (meterRecordJson.has("powerTotal")) {
				meterRecord.setPowerTotal(Double.parseDouble(meterRecordJson.getString("powerTotal")));
			}
			if (meterRecordJson.has("powerAiguille")) {
				meterRecord.setPowerAiguille(Double.parseDouble(meterRecordJson.getString("powerAiguille")));
			}
			if (meterRecordJson.has("powerPeak")) {
				meterRecord.setPowerPeak(Double.parseDouble(meterRecordJson.getString("powerPeak")));
			}
			if (meterRecordJson.has("powerFlat")) {
				meterRecord.setPowerFlat(Double.parseDouble(meterRecordJson.getString("powerFlat")));
			}
			if (meterRecordJson.has("powerGrain")) {
				meterRecord.setPowerGrain(Double.parseDouble(meterRecordJson.getString("powerGrain")));
			}
			if (meterRecordJson.has("idleTotal")) {
				meterRecord.setIdleTotal(Double.parseDouble(meterRecordJson.getString("idleTotal")));
			}
			if (meterRecordJson.has("addMeterRecordDate")) {
				meterRecord.setAddMeterRecordDate(meterRecordJson.getString("addMeterRecordDate"));
				meterRecord.setAddMeterRecordDTTM(Tools.str2DateTime(meterRecordJson.getString("addMeterRecordDate")));
			}
			if (meterRecordJson.has("meterMan")) {
				meterRecord.setMeterMan(meterRecordJson.getString("meterMan"));
			}
			if (meterRecordJson.has("createUser")) {
				meterRecord.setCreateUser(meterRecordJson.getString("createUser"));
			} else {
				meterRecord.setCreateUser(userID);
			}
			if (meterRecordJson.has("createDTTM")) {
				meterRecord.setCreateDTTM(Tools.str2DateTime(meterRecordJson.getString("createDTTM")));
			} else {
				meterRecord.setCreateDTTM(date);
			}
			meterRecords.add(meterRecord);
		}
		return meterRecords;
	}

	@SuppressWarnings("unchecked")
	public List<MeterRecord> getMeterInfo(MeterRecord meterRecord) throws Exception {
		return (List<MeterRecord>) this.getDaoSupport().findForList("T_MeterManage.getMeterInfo", meterRecord);
	}

	public void getLastMeterRecord(MeterRecord meterRecord) throws Exception {
		MeterRecord meterRecord2 = (MeterRecord) this.getDaoSupport().findForObject("T_MeterRecord.getLastRecordForMeter", meterRecord);
		if (meterRecord2 == null) {
			meterRecord.setIdleTotal(0);
			meterRecord.setPowerTotal(0);
			meterRecord.setPowerGrain(0);
			meterRecord.setPowerPeak(0);
			meterRecord.setPowerAiguille(0);
			meterRecord.setPowerFlat(0);
			meterRecord.setMeterDate("");
			meterRecord.setMeterTime("");
		} else {
			meterRecord.setIdleTotal(meterRecord2.getIdleTotal());
			meterRecord.setPowerTotal(meterRecord2.getPowerTotal());
			meterRecord.setPowerGrain(meterRecord2.getPowerGrain());
			meterRecord.setPowerPeak(meterRecord2.getPowerPeak());
			meterRecord.setPowerAiguille(meterRecord2.getPowerAiguille());
			meterRecord.setPowerFlat(meterRecord2.getPowerFlat());
			if (meterRecord2.getMeterDate() == null) {
				meterRecord.setMeterDate("");
			} else {
				meterRecord.setMeterDate(meterRecord2.getMeterDate());
			}
			if (meterRecord2.getMeterTime() == null) {
				meterRecord.setMeterTime("");
			} else {
				meterRecord.setMeterTime(meterRecord2.getMeterTime());
			}
		}
	}

	public String addMeterRecordImg(MultipartFile fileSrc, String meterTime, String chargingStationID, String meterCode, String meterType, String avatar_data) throws IOException {
		String [] meterTimeArr = meterTime.split("[^\\d]");
		JSONObject json = JSONObject.fromObject(avatar_data);
		String filePath = File.separator.concat("meterrecord").concat(File.separator)
						.concat(meterTimeArr[0]).concat(File.separator).concat(meterTimeArr[1])
						.concat(File.separator).concat(meterTimeArr[2]).concat(File.separator)
						.concat(chargingStationID).concat(File.separator);
		String meterTimeAfter = meterTimeArr[0] + meterTimeArr[1] + meterTimeArr[2] + meterTimeArr[3] + meterTimeArr[4] + meterTimeArr[5];
		String fileName = "";
		switch (Integer.parseInt(meterType)) {
		case 0:
			fileName = chargingStationID.concat(meterTimeAfter).concat("date").concat(meterCode).concat(".png");
			break;
		case 1:
			fileName = chargingStationID.concat(meterTimeAfter).concat("time").concat(meterCode).concat(".png");
			break;
		case 2:
			fileName = chargingStationID.concat(meterTimeAfter).concat("total").concat(meterCode).concat(".png");
			break;
		case 3:
			fileName = chargingStationID.concat(meterTimeAfter).concat("sharp").concat(meterCode).concat(".png");
			break;
		case 4:
			fileName = chargingStationID.concat(meterTimeAfter).concat("peak").concat(meterCode).concat(".png");
			break;
		case 5:
			fileName = chargingStationID.concat(meterTimeAfter).concat("flat").concat(meterCode).concat(".png");
			break;
		case 6:
			fileName = chargingStationID.concat(meterTimeAfter).concat("valley").concat(meterCode).concat(".png");
			break;
		case 7:
			fileName = chargingStationID.concat(meterTimeAfter).concat("idle").concat(meterCode).concat(".png");
			break;
		default:
			break;
		}
		if (!"".equals(fileName)) {
			File file = new File(filePath);
			if (!file.exists()  && !file .isDirectory()) {
			    file.mkdirs();
			}
			String filePath1 = filePath.concat(fileName);
			file = new File(filePath1);
			if (!file.exists()) {
				file.createNewFile();
			} else {
				file.delete();
				file.createNewFile();
			}
			FileOutputStream outputStream = new FileOutputStream(file, true);
			outputStream.write(fileSrc.getBytes());
			outputStream.flush();
			outputStream.close();
			BufferedImage bufferedimage = ImageIO.read(file);
			BufferedImage bufferedImage2 = ImageCut.rotateImage(bufferedimage, json.getInt("rotate"));
			ImageIO.write(bufferedImage2, "png", file);
			ImageCut.abscut(file, filePath1, json.getInt("x"), json.getInt("y"), json.getInt("width"), json.getInt("height"));
//			Thumbnails.of(file).size(160, 90).toFile(filePath.concat(Const.Meter_IMG_SMALL).concat(fileName));
			return filePath.concat(fileName);
		} else {
			return "";
		}
	}

	public void getMeterImg(String meterCode, String meterTime, String chargingStationID, String meterType, HttpServletResponse response){
		String [] meterTimeArr = meterTime.split("[^\\d]");
		String filePath = Const.BALANCE_PATH.concat("meterrecord").concat(File.separator)
				.concat(meterTimeArr[0]).concat(File.separator).concat(meterTimeArr[1])
				.concat(File.separator).concat(meterTimeArr[2]).concat(File.separator)
				.concat(chargingStationID).concat(File.separator);
		String meterTimeAfter = meterTimeArr[0] + meterTimeArr[1] + meterTimeArr[2] + meterTimeArr[3] + meterTimeArr[4] + meterTimeArr[5];
		String fileName = "";
		switch (Integer.parseInt(meterType)) {
		case 0:
			fileName = chargingStationID.concat(meterTimeAfter).concat("date").concat(meterCode).concat(".png");
			break;
		case 1:
			fileName = chargingStationID.concat(meterTimeAfter).concat("time").concat(meterCode).concat(".png");
			break;
		case 2:
			fileName = chargingStationID.concat(meterTimeAfter).concat("total").concat(meterCode).concat(".png");
			break;
		case 3:
			fileName = chargingStationID.concat(meterTimeAfter).concat("sharp").concat(meterCode).concat(".png");
			break;
		case 4:
			fileName = chargingStationID.concat(meterTimeAfter).concat("peak").concat(meterCode).concat(".png");
			break;
		case 5:
			fileName = chargingStationID.concat(meterTimeAfter).concat("flat").concat(meterCode).concat(".png");
			break;
		case 6:
			fileName = chargingStationID.concat(meterTimeAfter).concat("valley").concat(meterCode).concat(".png");
			break;
		case 7:
			fileName = chargingStationID.concat(meterTimeAfter).concat("idle").concat(meterCode).concat(".png");
			break;
		default:
			break;
		}
		filePath = filePath.concat(fileName);
		try {
			File downLoadPath = new File(filePath);
			if (downLoadPath.exists()) {
				FileDownload.fileDownload(response, filePath, fileName);
			}
			downLoadPath = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void deleteMeterImg(String meterTime, String chargingStationID){
		String [] meterTimeArr = meterTime.split("[^\\d]");
		String filePath = Const.BALANCE_PATH.concat("meterrecord").concat(File.separator)
				.concat(meterTimeArr[0]).concat(File.separator).concat(meterTimeArr[1])
				.concat(File.separator).concat(meterTimeArr[2]).concat(File.separator)
				.concat(chargingStationID);
		File file = new File(filePath);
		if (file.exists()) {
			if (file.isFile()) {
			      file.delete();
			} else if (file.isDirectory()) {
				File[] files = file.listFiles();
				for (int i = 0;i < files.length;i ++) {
					files[i].delete();
				}
				file.delete();
			}
		}
	}
}
